#pragma once
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <mutex>
#include <assert.h>
#include <algorithm>
#include <fstream>
#include <jsoncpp/json/json.h>
#include "../comm/Log.hpp"
#include "oj_model_2.hpp"
#include "oj_view.hpp"
#include "../comm/Util.hpp"
#include "../comm/httplib.h"
namespace ns_control
{
    using namespace ns_model;
    using namespace ns_view;
    using namespace ns_log;
    using namespace ns_util;
    using namespace httplib;
    class Machine
    {
    public:
        Machine() : ip(""), port(0), load(0), mtx(nullptr)
        {
        }
        ~Machine()
        {
        }
        //负载重置
        void ResetLoad()
        {
            if(mtx) mtx->lock();
            load=0;
            if(mtx) mtx->unlock();
        }
        // 负载增加
        void IncLoad()
        {
            if (mtx)
                mtx->lock();
            ++load;
            if (mtx)
                mtx->unlock();
        }
        // 负载减少
        void DesLoad()
        {
            if (mtx)
                mtx->lock();
            --load;
            if (mtx)
                mtx->unlock();
        }
        // 获取负载
        uint64_t GetLoad()
        {
            uint64_t _load;
            if (mtx)
                mtx->lock();
            _load = load;
            if (mtx)
                mtx->unlock();
            return _load;
        }

    public:
        std::string ip;  // 主机的ip
        int port;        // 主机的port
        uint64_t load;   // 主机的负载
        std::mutex *mtx; // mutex对象禁止拷贝，使用指针方便Machine对象拷贝
    };
    const std::string machine_list = "./conf/machine_list.conf";
    class LoadBlance
    {
    private:
        std::vector<Machine> machines;    // 存放所有主机
        std::vector<int> online_machine;  // 存在所有在线主机的下标
        std::vector<int> offline_machine; // 存放所有离线主机的下表
        std::mutex mtx;

    public:
        LoadBlance()
        {
            assert(LoadMachines(machine_list));
        }
        ~LoadBlance()
        {
        }
        // 加载所有的编译主机的配置信息
        bool LoadMachines(const std::string &machine_list)
        {
            std::ifstream in(machine_list);
            if (!in.is_open())
            {
                LOG(FATAL) << "打开编译主机配置文件失败.." << "\n";
                return false;
            }
            std::string line;
            while (getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::SplitString(line, &tokens, ":");
                Machine m;
                m.ip = tokens[0];
                m.port = atoi(tokens[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();
                // 先加入online信息，这样下标与主机编号对应
                online_machine.push_back(machines.size());
                machines.push_back(m);
            }
            in.close();
            LOG(INFO) << "编译主机配置信息加载成功" << "\n";
            return true;
        }
        // 轮询选择最小负载的机器
        bool SmartChoice(int *id, Machine **machine)
        {
            mtx.lock();
            int online_num = online_machine.size();
            if (online_num == 0)
            {

                LOG(FATAL) << "编译功能主机全部离线，请负责运维的同志查看" << "\n";
                mtx.unlock();
                return false;
            }

            *id = online_machine[0];
            *machine = &machines[online_machine[0]];
            uint64_t min_load = (*machine)->GetLoad();

            for (int i = 0; i < online_num; i++)
            {
                uint64_t curr_load = machines[online_machine[i]].GetLoad();
                if (min_load > curr_load)
                {
                    *id = online_machine[i];
                    *machine = &machines[online_machine[i]];
                }
            }
            mtx.unlock();
            return true;
        }
        void ShowMachines()
        {
            mtx.lock();
            std::cout << "上线的主机个数为:" << online_machine.size() << ",编号为: " << std::endl;
            // 上线的主机
            for (auto &online : online_machine)
            {
                std::cout << online << " ";
            }
            std::cout << std::endl;
            std::cout << "离线的主机个数为:" << offline_machine.size() << ",编号为: " << std::endl;
            // 上线的主机
            for (auto &offline : offline_machine)
            {
                std::cout << offline << " ";
            }
            std::cout << std::endl;
            mtx.unlock();
        }
        // 上线主机
        void OnlineMachine()
        {
            mtx.lock();
            online_machine.insert(online_machine.end(),offline_machine.begin(),offline_machine.end());
            offline_machine.erase(offline_machine.begin(),offline_machine.end());
            mtx.unlock();
        }
        // 离线主机
        void OffMachine(int id)
        {
            mtx.lock();
            for (auto iter = online_machine.begin(); iter != online_machine.end(); iter++)
            {
                if (*iter == id)
                {
                    machines[id].ResetLoad();
                    online_machine.erase(iter);
                    offline_machine.push_back(id);
                    break;
                }
            }
            mtx.unlock();
        }
    };
    class Control
    {
    public:
        Control()
        {
        }
        ~Control()
        {
        }
        bool AllQuestions(std::string *html)
        {
            bool ret = true;
            std::vector<struct Question> all;
            if (model_.GetAllQuestion(&all))
            {
                sort(all.begin(), all.end(), [](const struct Question &a1, const struct Question &a2)
                     { return atoi(a1.number.c_str()) < atoi(a2.number.c_str()); });
                view_.AllExpandHtml(all, html);
            }
            else
            {
                *html = "获取网页题目失败..";
                ret = false;
            }
            return ret;
        }
        bool OneQuestion(const std::string number, std::string *html)
        {
            bool ret = true;
            Question q;
            if (model_.GetOneQuestion(number, &q))
            {
                view_.OneExpandHtml(q, html);
            }
            else
            {
                *html = "网页题目" + number + "不存在";
                ret = false;
            }
            return ret;
        }
        void Judge(const std::string &number, const std::string &in_json, std::string *out_json)
        {
            // 0.根据题目编号，拿到题目细节
            Question q;
            model_.GetOneQuestion(number, &q); // 拿到题目细节
            // 1.in_json反序列化，得到题目id，得到用户源代码，input
            Json::Reader reader;
            Json::Value in_value;
            reader.parse(in_json, in_value);
            Json::Value compile_value;
            // 2.组装code和tail
            std::string code = in_value["code"].asString();
            compile_value["input"] = in_value["input"].asString();
            compile_value["code"] = code + "\n" + q.tail;
            compile_value["cpu_limit"] = q.cpu_limit;
            compile_value["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile_value);
            // 3.选择负载最低的主机
            int id = 0;
            Machine *m = nullptr;
            while (true)
            {
                // 4.发起http请求给主机，得到结果
                if (loadblance_.SmartChoice(&id, &m))
                {
                    m->IncLoad();
                    LOG(INFO) << " 选择主机成功, 主机id: " << id << " 详情: " << m->ip << ":" << m->port << " 当前主机的负载是: " << m->GetLoad() << "\n";
                    // 选择主机成功
                    Client cli(m->ip, m->port);
                    if (auto res = cli.Post("/compile_and_run", compile_string, "application/json;charset=utf-8"))
                    {
                        if (res->status == 200)
                        {
                            // 5.返回给上层发送给用户
                            *out_json = res->body;
                            m->DesLoad();
                            break;
                        }
                    }
                }
                else
                {
                    LOG(ERROR) << " 当前请求的主机id: " << id << " 详情: " << m->ip << ":" << m->port << " 可能已经离线" << "\n";
                    loadblance_.OffMachine(id);
                    loadblance_.ShowMachines();
                }
            }
        }

    private:
        Model model_;           // 提供后台数据
        View view_;             // 渲染数据,形成渲染后的html
        LoadBlance loadblance_; // 负载均衡器
    };
}